// 引入axios
const axios = require('axios');

// 创建axios实例
const httpService = axios.create({
    // 请求超时时间
    timeout: 18000 // 需自定义
});

httpService.interceptors.response.use(
    response => {
        return response.data;
    }
);
/*网络请求部分*/

/*
 *  get请求
 *  url:请求地址
 *  params:参数
 * */
function get(url, params = {}) {
    return new Promise((resolve, reject) => {
        httpService({
            url: url,
            method: 'get',
            params: params
        }).then(response => {
            resolve(response);
        }).catch(error => {
            reject(error);
        });
    });
}

function postJson(url, params = {}, headers = {}) {
    return new Promise((resolve, reject) => {
        httpService({
            url: url,
            method: 'post',
            data: params,
            headers: headers
        }).then(response => {
            resolve(response);
        }).catch(error => {
            reject(error);
        });
    });
}

function postForm(url, params = {}, headers = {}) {
    return new Promise((resolve, reject) => {
        httpService({
            url: url,
            method: 'post',
            data: params,
            transformRequest: [function (data) {
                let ret = ''
                for (let it in data) {
                    if (data[it] === undefined || data[it] === null) {
                        ret += encodeURIComponent(it) + '=' + '&';
                    } else {
                        ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&';
                    }
                }
                return ret;
            }],
            headers: headers
        }).then(response => {
            resolve(response);
        }).catch(error => {
            reject(error);
        });
    });
}

function postJson4Log(url, params = {}, headers = {}) {
    return new Promise((resolve, reject) => {
        httpService({
            url: url,
            method: 'post',
            data: params,
            headers: headers,
            timeout: 5000
        }).then(response => {
            resolve(response);
        }).catch(error => {
            console.log('trace log send failed:', error.message);
        });
    });
}

module.exports = {get, postJson, postForm, postJson4Log}